{% extends "base.html" %}

{% block title %}学生仪表盘 - IT课程数据分析系统{% endblock %}

{% block extra_css %}
<style>
    .dashboard-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }
    
    .stat-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 8px;
        padding: 1.5rem;
        text-align: center;
    }
    
    .stat-card h3 {
        font-size: 0.9rem;
        opacity: 0.9;
        margin-bottom: 0.5rem;
    }
    
    .stat-card .value {
        font-size: 2.5rem;
        font-weight: 700;
        margin-bottom: 0.25rem;
    }
    
    .chart-container {
        height: 400px;
        width: 100%;
    }
    
    .recommendations {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 1rem;
    }
    
    .recommendation-card {
        background: white;
        border: 1px solid #e0e0e0;
        border-radius: 8px;
        padding: 1rem;
        transition: all 0.3s;
    }
    
    .recommendation-card:hover {
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        transform: translateY(-2px);
    }
    
    .recommendation-card h4 {
        color: #2c3e50;
        margin-bottom: 0.5rem;
    }
    
    .recommendation-card .course-code {
        color: #7f8c8d;
        font-size: 0.85rem;
        margin-bottom: 0.5rem;
    }
    
    .recommendation-card .reason {
        font-size: 0.85rem;
        color: #3498db;
        margin-bottom: 1rem;
    }
    
    .recommendation-actions {
        display: flex;
        gap: 0.5rem;
    }
    
    .recommendation-actions button {
        flex: 1;
        padding: 0.5rem;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 0.85rem;
    }
    
    .btn-like {
        background: #2ecc71;
        color: white;
    }
    
    .btn-dislike {
        background: #e74c3c;
        color: white;
    }
    
    /* 学习预警样式 */
    .alert-section {
        margin-bottom: 1rem;
    }
    
    .alert-section-title {
        color: #2c3e50;
        font-size: 1.1rem;
        font-weight: 600;
        margin-bottom: 0.75rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    
    .alert-list {
        display: grid;
        gap: 0.75rem;
    }
    
    .alert-item {
        background: #fff5f5;
        border-left: 3px solid #e74c3c;
        padding: 1rem;
        border-radius: 4px;
        display: flex;
        justify-content: space-between;
        align-items: start;
    }
    
    .alert-item.warning {
        background: #fffaf0;
        border-left-color: #f39c12;
    }
    
    .alert-item.info {
        background: #f0f8ff;
        border-left-color: #3498db;
    }
    
    .alert-info {
        flex: 1;
    }
    
    .alert-course {
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 0.25rem;
    }
    
    .alert-message {
        color: #7f8c8d;
        font-size: 0.9rem;
    }
    
    .suggestions-section {
        margin-top: 1.5rem;
        padding-top: 1.5rem;
        border-top: 2px solid #e0e0e0;
    }
    
    .suggestions-list {
        display: grid;
        gap: 0.5rem;
        margin-top: 0.75rem;
    }
    
    .suggestion-item {
        background: #f0f8ff;
        padding: 0.75rem 1rem;
        border-radius: 4px;
        display: flex;
        align-items: center;
        gap: 0.5rem;
        color: #2c3e50;
        font-size: 0.95rem;
    }
    
    .suggestion-item::before {
        content: '💡';
        font-size: 1.2rem;
    }
    
    /* 推荐模块增强 */
    .recommendation-toolbar {
        display: flex;
        gap: 0.75rem;
        align-items: center;
        margin: 0.5rem 0 1rem 0;
        flex-wrap: wrap;
    }
    .toolbar-input {
        padding: 0.5rem;
        border: 1px solid #e0e0e0;
        border-radius: 6px;
        min-width: 240px;
    }
    .toolbar-select {
        padding: 0.5rem;
        border: 1px solid #e0e0e0;
        border-radius: 6px;
    }
    .chip-toggle {
        padding: 0.4rem 0.75rem;
        border: 1px solid #e0e0e0;
        border-radius: 999px;
        background: #ffffff;
        cursor: pointer;
        font-size: 0.85rem;
    }
    .chip-toggle.active {
        background: #2ecc71;
        color: white;
        border-color: #2ecc71;
    }
    .btn-outline {
        background: #ffffff;
        border: 1px solid #e0e0e0;
        color: #2c3e50;
    }
    .btn-small {
        padding: 0.4rem 0.6rem;
        font-size: 0.85rem;
        border-radius: 4px;
    }
    .btn-fav {
        background: #f1c40f;
        color: #2c3e50;
    }
    
    /* 简易模态框 */
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        z-index: 1000;
        justify-content: center;
        align-items: center;
    }
    .modal-content {
        background: white;
        border-radius: 8px;
        padding: 1.5rem;
        width: 90%;
        max-width: 520px;
        box-shadow: 0 8px 24px rgba(0,0,0,0.2);
    }
</style>
{% endblock %}

{% block content %}
<h2 style="margin-bottom: 1.5rem;">学生仪表盘</h2>

<div id="loading" class="loading">
    <div class="spinner"></div>
    <p>加载中...</p>
</div>

<div id="dashboard-content" style="display: none;">
    <!-- 统计卡片 -->
    <div class="dashboard-grid">
        <div class="stat-card">
            <h3>累积GPA</h3>
            <div class="value" id="gpa-value">-</div>
            <p>总成绩绩点</p>
        </div>
        <div class="stat-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
            <h3>已完成课程</h3>
            <div class="value" id="completed-courses">-</div>
            <p>门课程</p>
        </div>
        <div class="stat-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
            <h3>平均成绩</h3>
            <div class="value" id="average-score">-</div>
            <p>分</p>
        </div>
    </div>
    
    <!-- 学习预警卡片 -->
    <div id="alerts-card" style="display:none;margin-bottom:1.5rem;">
        <div class="card" style="border-left: 4px solid #e74c3c;">
            <div class="card-title" style="color:#e74c3c;">⚠️ 学习预警</div>
            <div id="alerts-content"></div>
        </div>
    </div>
    
    <!-- GPA趋势图 -->
    <div class="card">
        <div class="card-title">学期GPA趋势</div>
        <div id="gpa-chart" class="chart-container"></div>
    </div>
    
    <!-- 成绩分布 -->
    <div class="card">
        <div class="card-title">各科成绩分布</div>
        <div id="scores-chart" class="chart-container"></div>
    </div>
    
    <!-- 课程推荐 -->
    <div class="card">
        <div class="card-title">为您推荐的课程</div>
        <div class="recommendation-toolbar">
            <input id="rec-search" class="toolbar-input" placeholder="搜索课程名称/代码/描述">
            <select id="rec-sort" class="toolbar-select">
                <option value="relevance">按相关性</option>
                <option value="name_asc">名称 A→Z</option>
                <option value="name_desc">名称 Z→A</option>
                <option value="credits_desc">学分 高→低</option>
                <option value="credits_asc">学分 低→高</option>
            </select>
            <button id="toggle-unenrolled" class="chip-toggle active" title="只看未学过">📘 未学过</button>
            <button id="toggle-conflict" class="chip-toggle" title="排除时间冲突">⏰ 排除冲突</button>
            <button id="toggle-favorites" class="chip-toggle" title="只看收藏">⭐ 只看收藏</button>
            <button id="rec-refresh" class="btn-small btn-outline">刷新</button>
        </div>
        <div id="recommendations" class="recommendations"></div>
        <div id="rec-footer" style="margin-top:0.75rem;text-align:center;">
            <button id="rec-load-more" class="btn-small btn-outline" style="display:none;">加载更多</button>
        </div>
    </div>

    <!-- 反馈提示模态框 -->
    <div id="feedback-modal" class="modal">
        <div class="modal-content">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:0.5rem;">
                <h3 style="margin:0;">反馈已提交</h3>
                <button id="feedback-close" class="btn btn-outline btn-small">关闭</button>
            </div>
            <p id="feedback-text" style="color:#2c3e50;line-height:1.8;">感谢您的反馈，我们将优化推荐结果。</p>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js"></script>
<script>
    let currentStudentId = null;
    // 推荐模块本地状态
    let allRecommendations = [];
    let shownCount = 0;
    const PAGE_SIZE = 6;
    const FAVORITES_KEY = 'rec_favorites';
    const HIDDEN_KEY = 'rec_hidden';
    let favoriteSet = new Set(JSON.parse(localStorage.getItem(FAVORITES_KEY) || '[]'));
    let hiddenSet = new Set(JSON.parse(localStorage.getItem(HIDDEN_KEY) || '[]'));
    
    async function loadDashboard() {
        try {
            const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
            currentStudentId = userInfo.id;
            
            if (!currentStudentId) {
                window.location.href = '/login';
                return;
            }
            
            // 先显示内容，再绘制图表，避免容器宽度为0导致图表过窄
            document.getElementById('loading').style.display = 'none';
            document.getElementById('dashboard-content').style.display = 'block';
            
            // 加载学习预警
            await loadLearningAlerts();
            
            // 加载GPA趋势
            await loadGPATrend();
            
            // 加载学业表现
            await loadPerformance();
            
            // 加载推荐
            await loadRecommendations();
            
        } catch (error) {
            showAlert('加载失败: ' + error.message, 'error');
        }
    }
    
    async function loadGPATrend() {
        try {
            const data = await apiRequest(`/analytics/students/${currentStudentId}/gpa_trend`);
            
            if (data.success) {
                const gpaData = data.data;
                
                // 更新统计卡片
                document.getElementById('gpa-value').textContent = gpaData.cumulative_gpa.toFixed(2);
                document.getElementById('completed-courses').textContent = gpaData.courses_completed;
                
                // 绘制GPA趋势图
                const semesters = Object.keys(gpaData.semester_gpa);
                const gpas = Object.values(gpaData.semester_gpa);
                
                const gpaDom = document.getElementById('gpa-chart');
                const chart = echarts.init(gpaDom);
                chart.setOption({
                    tooltip: {
                        trigger: 'axis'
                    },
                    xAxis: {
                        type: 'category',
                        data: semesters,
                        axisLabel: {
                            rotate: 45
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: 'GPA',
                        min: 0,
                        max: 4
                    },
                    series: [{
                        data: gpas,
                        type: 'line',
                        smooth: true,
                        areaStyle: {
                            opacity: 0.3
                        },
                        lineStyle: {
                            color: '#667eea',
                            width: 3
                        },
                        itemStyle: {
                            color: '#667eea'
                        }
                    }]
                });
                
                // 在窗口大小变化时自适应
                window.addEventListener('resize', () => chart.resize());
            }
        } catch (error) {
            console.error('加载GPA趋势失败:', error);
        }
    }
    
    async function loadPerformance() {
        try {
            const data = await apiRequest(`/analytics/students/${currentStudentId}/performance`);
            
            if (data.success) {
                const performance = data.data && data.data.performance ? data.data.performance : null;
                if (!performance) {
                    console.warn('performance payload missing');
                    return;
                }
                
                // 更新平均成绩
                if (typeof performance.average_score === 'number') {
                    document.getElementById('average-score').textContent = performance.average_score.toFixed(1);
                }
                
                // 获取学生详细信息绘制成绩分布
                const studentData = await apiRequest(`/students/${currentStudentId}`);
                const courseList = (studentData.success && studentData.data && Array.isArray(studentData.data.courses)) ? studentData.data.courses : [];
                if (courseList.length === 0) {
                    document.getElementById('scores-chart').innerHTML = '<div style="color:#7f8c8d;text-align:center;padding:2rem;">暂无成绩数据</div>';
                } else {
                    const scores = courseList
                        .filter(c => typeof c.score === 'number')
                        .map(c => ({
                            name: c.course ? c.course.name : '未知课程',
                            score: c.score
                        }));
                    
                    const scoresDom = document.getElementById('scores-chart');
                    const scoresChart = echarts.init(scoresDom);
                    scoresChart.setOption({
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        grid: {
                            bottom: '25%',  // 增加底部空间以容纳旋转的标签
                            left: '10%',
                            right: '10%',
                            top: '10%'
                        },
                        xAxis: {
                            type: 'category',
                            data: scores.map(s => s.name),
                            axisLabel: {
                                rotate: 45,
                                interval: 0,
                                fontSize: 11,  // 稍微减小字体以适应更多标签
                                color: '#666'
                            }
                        },
                        yAxis: {
                            type: 'value',
                            name: '分数',
                            min: 0,
                            max: 100
                        },
                        series: [{
                            data: scores.map(s => s.score),
                            type: 'bar',
                            itemStyle: {
                                color: function(params) {
                                    const score = params.value;
                                    if (score >= 90) return '#2ecc71';
                                    if (score >= 80) return '#3498db';
                                    if (score >= 70) return '#f39c12';
                                    if (score >= 60) return '#e67e22';
                                    return '#e74c3c';
                                }
                            }
                        }]
                    });
                    window.addEventListener('resize', () => scoresChart.resize());
                }
            }
        } catch (error) {
            console.error('加载学业表现失败:', error);
        }
    }
    
    async function loadRecommendations(fetchRemote = true) {
        try {
            if (fetchRemote) {
                // 携带后端真实相关性与筛选参数
                const onlyUnenrolled = document.getElementById('toggle-unenrolled')?.classList.contains('active');
                const conflict = document.getElementById('toggle-conflict')?.classList.contains('active');
                // 时间冲突筛选可选参数：用当前学期常见时间段作为默认占位，不传则后端不筛
                const params = new URLSearchParams();
                if (onlyUnenrolled) params.append('only_unenrolled', 'true'); else params.append('only_unenrolled', 'false');
                if (conflict) {
                    // 这里示例：如果学生当前查看的是周一1-2节，可在真实页面中由选择器提供
                    const day = localStorage.getItem('rec_conflict_day');
                    const start = localStorage.getItem('rec_conflict_start');
                    const end = localStorage.getItem('rec_conflict_end');
                    if (day && start && end) {
                        params.append('conflict_check', 'true');
                        params.append('day', day);
                        params.append('start_slot', start);
                        params.append('end_slot', end);
                    }
                }
                const data = await apiRequest(`/recommendations/users/${currentStudentId}?${params.toString()}`);
                if (data.success) {
                    allRecommendations = Array.isArray(data.data.recommendations) ? data.data.recommendations : [];
                }
            }
            renderRecommendations(true);
        } catch (error) {
            console.error('加载推荐失败:', error);
        }
    }

    function applyRecFiltersSortSearch(list) {
        const q = (document.getElementById('rec-search').value || '').toLowerCase().trim();
        const onlyFav = document.getElementById('toggle-favorites').classList.contains('active');
        const sort = document.getElementById('rec-sort').value;
        
        let filtered = list.filter(item => !hiddenSet.has(String(item.id)));
        if (q) {
            filtered = filtered.filter(c =>
                (c.name && c.name.toLowerCase().includes(q)) ||
                (c.code && c.code.toLowerCase().includes(q)) ||
                (c.description && c.description.toLowerCase().includes(q)) ||
                (c.recommendation_reason && c.recommendation_reason.toLowerCase().includes(q))
            );
        }
        if (onlyFav) {
            filtered = filtered.filter(c => favoriteSet.has(String(c.id)));
        }
        const by = {
            'name_asc': (a,b)=> (a.name||'').localeCompare(b.name||''),
            'name_desc': (a,b)=> (b.name||'').localeCompare(a.name||''),
            'credits_desc': (a,b)=> (b.credits||0) - (a.credits||0),
            'credits_asc': (a,b)=> (a.credits||0) - (b.credits||0),
        }[sort];
        if (sort === 'relevance') {
            filtered.sort((a,b)=> (b.relevance_score||0) - (a.relevance_score||0));
        }
        if (by) filtered.sort(by);
        return filtered;
    }

    function courseCardHtml(course) {
        const isFav = favoriteSet.has(String(course.id));
        return `
            <div class="recommendation-card" data-id="${course.id}">
                <h4>${course.name}</h4>
                <div class="course-code">${course.code || '-'} | ${course.credits || 0} 学分</div>
                <div class="reason">${course.recommendation_reason || ''}</div>
                <p style="font-size:0.85rem;color:#7f8c8d;margin-bottom:1rem;">
                    ${course.description || '暂无描述'}
                </p>
                <div class="recommendation-actions">
                    <button class="btn-like" onclick="submitFeedback(${course.id}, 'like')">👍 感兴趣</button>
                    <button class="btn-dislike" onclick="hideRecommendation(${course.id})">🛑 不再推荐</button>
                </div>
                <div style="display:flex;gap:0.5rem;margin-top:0.5rem;">
                    <button class="btn-small ${isFav ? 'btn-fav' : 'btn-outline'}" onclick="toggleFavorite(${course.id})">${isFav ? '⭐ 已收藏' : '☆ 收藏'}</button>
                    <a class="btn-small btn-outline" href="/courses/${course.id}" target="_blank">查看详情</a>
                </div>
            </div>`;
    }

    function renderRecommendations(reset = false) {
        const container = document.getElementById('recommendations');
        const loadMoreBtn = document.getElementById('rec-load-more');
        const list = applyRecFiltersSortSearch(allRecommendations);
        if (reset) {
            shownCount = 0;
            container.innerHTML = '';
        }
        if (list.length === 0) {
            container.innerHTML = '<p style="text-align:center;color:#7f8c8d;">暂无推荐课程</p>';
            loadMoreBtn.style.display = 'none';
            return;
        }
        const nextCount = Math.min(list.length, shownCount + PAGE_SIZE);
        const slice = list.slice(shownCount, nextCount);
        if (reset) {
            container.innerHTML = slice.map(courseCardHtml).join('');
        } else {
            container.insertAdjacentHTML('beforeend', slice.map(courseCardHtml).join(''));
        }
        shownCount = nextCount;
        loadMoreBtn.style.display = shownCount < list.length ? 'inline-block' : 'none';
    }

    // 收藏/隐藏/刷新
    function toggleFavorite(id) {
        const key = String(id);
        if (favoriteSet.has(key)) favoriteSet.delete(key); else favoriteSet.add(key);
        localStorage.setItem(FAVORITES_KEY, JSON.stringify(Array.from(favoriteSet)));
        renderRecommendations(true);
    }
    function hideRecommendation(id) {
        const key = String(id);
        hiddenSet.add(key);
        localStorage.setItem(HIDDEN_KEY, JSON.stringify(Array.from(hiddenSet)));
        // 同步发送不感兴趣反馈，但不阻塞UI
        submitFeedback(id, 'dislike');
        renderRecommendations(true);
    }
    
    async function submitFeedback(courseId, feedbackType) {
        try {
            await apiRequest('/recommendations/feedback', {
                method: 'POST',
                body: JSON.stringify({
                    course_id: courseId,
                    feedback_type: feedbackType
                })
            });
            
            // 弹窗提示
            const modal = document.getElementById('feedback-modal');
            const textEl = document.getElementById('feedback-text');
            if (textEl) {
                textEl.textContent = feedbackType === 'like' ? '感谢您的点赞，我们将优先推荐类似课程。' : '已记录不感兴趣，我们将减少此类推荐。';
            }
            if (modal) {
                modal.style.display = 'flex';
            }
            // 点赞后如果已隐藏则恢复
            if (feedbackType === 'like') {
                const key = String(courseId);
                if (hiddenSet.has(key)) {
                    hiddenSet.delete(key);
                    localStorage.setItem(HIDDEN_KEY, JSON.stringify(Array.from(hiddenSet)));
                }
            }
            renderRecommendations(true);
            
        } catch (error) {
            showAlert('提交失败: ' + error.message, 'error');
        }
    }

    // 事件绑定
    window.addEventListener('DOMContentLoaded', () => {
        const searchEl = document.getElementById('rec-search');
        const sortEl = document.getElementById('rec-sort');
        const favToggle = document.getElementById('toggle-favorites');
        const refreshBtn = document.getElementById('rec-refresh');
        const loadMoreBtn = document.getElementById('rec-load-more');
        if (searchEl) searchEl.addEventListener('input', () => renderRecommendations(true));
        if (sortEl) sortEl.addEventListener('change', () => renderRecommendations(true));
        const toggleUnenrolled = document.getElementById('toggle-unenrolled');
        if (toggleUnenrolled) toggleUnenrolled.addEventListener('click', () => { toggleUnenrolled.classList.toggle('active'); loadRecommendations(false); renderRecommendations(true);});
        const toggleConflict = document.getElementById('toggle-conflict');
        if (toggleConflict) toggleConflict.addEventListener('click', () => { toggleConflict.classList.toggle('active'); loadRecommendations(true);});
        if (favToggle) favToggle.addEventListener('click', () => {
            favToggle.classList.toggle('active');
            renderRecommendations(true);
        });
        if (refreshBtn) refreshBtn.addEventListener('click', () => loadRecommendations(true));
        if (loadMoreBtn) loadMoreBtn.addEventListener('click', () => renderRecommendations(false));

        // 反馈模态框关闭
        const fbClose = document.getElementById('feedback-close');
        const fbModal = document.getElementById('feedback-modal');
        if (fbClose && fbModal) {
            fbClose.addEventListener('click', () => fbModal.style.display = 'none');
            window.addEventListener('click', (e) => { if (e.target === fbModal) fbModal.style.display = 'none'; });
        }
    });
    
    async function loadLearningAlerts() {
        try {
            const data = await apiRequest('/student/learning-alerts');
            
            if (data.success && data.data) {
                const alerts = data.data;
                
                // 如果有预警信息，显示预警卡片
                if (alerts.total_warnings > 0) {
                    document.getElementById('alerts-card').style.display = 'block';
                    
                    let html = '';
                    
                    // 成绩不及格预警
                    if (alerts.failing_courses && alerts.failing_courses.length > 0) {
                        html += `
                            <div class="alert-section">
                                <div class="alert-section-title">
                                    <span>🚨</span>
                                    <span>成绩预警 (${alerts.failing_courses.length}门)</span>
                                </div>
                                <div class="alert-list">
                        `;
                        alerts.failing_courses.forEach(alert => {
                            html += `
                                <div class="alert-item">
                                    <div class="alert-info">
                                        <div class="alert-course">${alert.course_name}</div>
                                        <div class="alert-message">${alert.message}</div>
                                    </div>
                                </div>
                            `;
                        });
                        html += `
                                </div>
                            </div>
                        `;
                    }
                    
                    // 出勤率低预警
                    if (alerts.low_attendance && alerts.low_attendance.length > 0) {
                        html += `
                            <div class="alert-section">
                                <div class="alert-section-title">
                                    <span>📅</span>
                                    <span>出勤预警 (${alerts.low_attendance.length}门)</span>
                                </div>
                                <div class="alert-list">
                        `;
                        alerts.low_attendance.forEach(alert => {
                            html += `
                                <div class="alert-item warning">
                                    <div class="alert-info">
                                        <div class="alert-course">${alert.course_name}</div>
                                        <div class="alert-message">${alert.message}</div>
                                    </div>
                                </div>
                            `;
                        });
                        html += `
                                </div>
                            </div>
                        `;
                    }
                    
                    // 综合风险预警
                    if (alerts.at_risk && alerts.at_risk.length > 0) {
                        html += `
                            <div class="alert-section">
                                <div class="alert-section-title">
                                    <span>⚠️</span>
                                    <span>综合风险 (${alerts.at_risk.length}门)</span>
                                </div>
                                <div class="alert-list">
                        `;
                        alerts.at_risk.forEach(alert => {
                            html += `
                                <div class="alert-item info">
                                    <div class="alert-info">
                                        <div class="alert-course">${alert.course_name}</div>
                                        <div class="alert-message">${alert.message}</div>
                                    </div>
                                </div>
                            `;
                        });
                        html += `
                                </div>
                            </div>
                        `;
                    }
                    
                    // 学习建议
                    if (alerts.suggestions && alerts.suggestions.length > 0) {
                        html += `
                            <div class="suggestions-section">
                                <div class="alert-section-title">
                                    <span>💡</span>
                                    <span>学习建议</span>
                                </div>
                                <div class="suggestions-list">
                        `;
                        alerts.suggestions.forEach(suggestion => {
                            html += `<div class="suggestion-item">${suggestion}</div>`;
                        });
                        html += `
                                </div>
                            </div>
                        `;
                    }
                    
                    document.getElementById('alerts-content').innerHTML = html;
                } else {
                    // 没有预警，隐藏卡片
                    document.getElementById('alerts-card').style.display = 'none';
                }
            }
        } catch (error) {
            console.error('加载学习预警失败:', error);
            // 预警加载失败不影响其他功能
        }
    }
    
    // 页面加载时执行
    window.addEventListener('DOMContentLoaded', loadDashboard);
</script>
{% endblock %}





